package com.company;

import com.company.model.result.BaseResult;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

/**
 * Created by tu on 2017/4/26.
 */
@ControllerAdvice
public class CompanyExceptionHandler {

  private static final Logger logger = LoggerFactory.getLogger(CompanyExceptionHandler.class);

  @ExceptionHandler(value = CompanyException.class)
  @ResponseBody
  public BaseResult<String> companyExceptionHandler(HttpServletRequest request, CompanyException e)
      throws Exception {
    String url = request.getRequestURL().toString();
    BaseResult<String> result = new BaseResult<>(e.getMessage(), url);
    logger.error("CompanyException", e);
    return result;
  }

  @ExceptionHandler(value = ValidationException.class)
  @ResponseStatus(HttpStatus.BAD_REQUEST)
  @ResponseBody
  public Object validationExceptionHandle(ValidationException e, HttpServletRequest request,
      HttpServletResponse response) {
    logger.error("ValidationException", e);
    return new BaseResult(e.getMessage(), request.getRequestURL().toString());
  }

  @ExceptionHandler(value = Exception.class)
  @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  public ModelAndView apiExceptionHandle(Exception e, HttpServletRequest request,
      HttpServletResponse response) {
    logger.error("Exception", e);
    ModelAndView mav = new ModelAndView();
    mav.addObject("exception", e);
    mav.addObject("url", request.getRequestURL());
    mav.setViewName("/error");
    return mav;
  }
}
